from mysql_utils import *
from functools import lru_cache
import jieba

# 载入自定义词典
jieba.load_userdict("userdict.txt")

@lru_cache(maxsize=None)
def get_keyword_link(key):
    """
    @summary: 连接数据库，得到关键词链接
    @param key: 关键词
    @return: 关键词的链接
    """
    mysql = MyPymysqlPool('dbMysql')
    query = 'SELECT link FROM keywords WHERE keyword=%s'
    link = mysql.getOne(query, key)
    mysql.dispose()
    return link['link'] if link else ''

def replace_keywords_with_links(text):
    """
    @summary: 将关键词替换成带链接的关键词
    @param text: 文本
    @return: [文本](链接)
    """
    words = list(jieba.cut(text, cut_all=False))

    for i, word in enumerate(words):
        link = get_keyword_link(word)
        if link:
            words[i] = f'[{word}]({link})'

    return ''.join(words)

def run_app(input_file, output_file):
    with open(input_file, 'r', encoding='utf-8') as f_input, open(output_file, 'w', encoding='utf-8') as f_output:
        # 避免一次文本过大，逐行处理文本
        for line in f_input:
            words = replace_keywords_with_links(line)
            f_output.write(''.join(words))

if __name__ == '__main__':
    run_app('input.md', 'output.md')